<template>
  <div id="training">
    <Breadcrumb content="培训管理" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getTrainingList" @search-click="getTrainingList"></vxe-input>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getTrainingList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="add()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="trainingBox">
            <vxe-table ref="trainingTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="trainingList" :row-config="{ isCurrent: true, isHover: true }" @current-change="currentChangeEvent" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="trainingName" title="培训主题"></vxe-column>
              <vxe-column field="trainingDate" title="培训时间"></vxe-column>
              <vxe-column field="address" title="培训地点"> </vxe-column>
              <vxe-column field="endDate" title="培训结束时间"> </vxe-column>
              <vxe-column field="trainingType" title="培训方式" :formatter="formatterType"> </vxe-column>
              <vxe-column field="seq" title="顺序"> </vxe-column>
              <vxe-column field="status" title="状态">
                <template #default="{ row }">
                  <el-tag size="small"> {{ formatterStatus(row.status) }}</el-tag>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="40">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <el-form ref="trainingFormRef" :model="trainingForm" :rules="trainingFormRules" label-width="100px" class="form-input-m baseForm" v-loading="showLoading" inline-message>
                <el-scrollbar style="height: 100%">
                  <el-form-item label="编码" prop="trainingCode">
                    <el-input v-model="trainingForm.trainingCode" placeholder="编码" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="培训主题" prop="trainingName"> <el-input v-model="trainingForm.trainingName" placeholder="培训主题" clearable></el-input> </el-form-item>
                  <el-form-item label="培训时间" prop="trainingDate">
                    <el-date-picker v-model="trainingForm.trainingDate" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="培训时间" clearable />
                  </el-form-item>
                  <el-form-item label="培训地点" prop="address"> <el-input v-model="trainingForm.address" placeholder="培训地点" clearable></el-input> </el-form-item>
                  <el-form-item label="培训结束时间" prop="endDate">
                    <el-date-picker v-model="trainingForm.endDate" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="培训结束时间" clearable />
                  </el-form-item>
                  <el-form-item label="培训目标" prop="target"> <el-input v-model="trainingForm.target" placeholder="培训目标" clearable></el-input> </el-form-item>
                  <el-form-item label="培训方式" prop="trainingType">
                    <el-select v-model="trainingForm.trainingType" placeholder="培训方式" style="width: 200px">
                      <el-option v-for="item in typeOptions" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="主持人" prop="hostName"> <el-input v-model="trainingForm.hostName" placeholder="主持人" clearable></el-input> </el-form-item>
                  <el-form-item label="记录人" prop="recorderName"> <el-input v-model="trainingForm.recorderName" placeholder="记录人" clearable></el-input> </el-form-item>
                  <el-form-item label="顺序" prop="seq">
                    <el-input-number v-model="trainingForm.seq" :min="1" :max="1000" />
                  </el-form-item>
                  <el-form-item label="参与人员" prop="sysUserList">
                    <el-select v-model="trainingForm.sysUserList" value-key="id" multiple placeholder="参会人" style="margin-right: 10px">
                      <el-option v-for="item in userOptions" :key="item.id" :label="item.realname" :value="item" />
                    </el-select>
                  </el-form-item>
                  <!-- <el-form-item label="采用知识" prop="isKnowledge">
                    <el-switch v-model="trainingForm.isKnowledge" inline-prompt active-text="是" inactive-text="否" :active-value="1" :inactive-value="0"></el-switch>
                  </el-form-item> -->
                  <el-form-item label="相关知识" prop="knowledgeIds">
                    <el-tree-select v-model="trainingForm.knowledgeIds" node-key="id" :data="knowledgeTreeOptions" :default-expanded-keys="[trainingForm.knowledgeIds]" :default-checked-keys="[trainingForm.knowledgeIds]" :render-after-expand="false" :props="defaultProps" show-checkbox multiple check-on-click-node style="margin-right: 10px" />
                  </el-form-item>
                  <el-form-item label="培训内容" prop="trainingContent"> <el-input v-model="trainingForm.trainingContent" type="textarea" placeholder="培训内容" clearable style="margin-right: 10px"></el-input> </el-form-item>
                  <el-form-item label="备注" prop="remake">
                    <el-input v-model="trainingForm.remake" type="textarea" placeholder="备注" clearable style="margin-right: 10px"></el-input>
                  </el-form-item>
                  <el-form-item class="form-footer">
                    <template #default>
                      <el-button type="primary" v-loading="saveLoading" @click="save()">暂存</el-button>
                      <el-button type="primary" v-loading="saveLoading" @click="release()">培训发布</el-button>
                      <el-button type="default" @click="add()">重置</el-button>
                    </template>
                  </el-form-item>
                  <div id="dbBarCharts" class="barChartss"></div>
                </el-scrollbar>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { isEmpty } from 'lodash';
import * as echarts from 'echarts';

let { proxy }: any = getCurrentInstance();
const trainingList = reactive([]);
const trainingForm = reactive({
  id: '',
  trainingCode: '',
  trainingName: '',
  trainingContent: '',
  trainingDate: '',
  address: '',
  endDate: '',
  target: '',
  trainingType: '',
  sysUserList: [],
  // isKnowledge: 0,
  knowledgeList: [],
  knowledgeIds: [],
  hostName: '',
  recorderName: '',
  seq: 0,
  signNo: 0,
  notSignNo: 0,
  refuseSignNo: 0,
  remake: '',
  status: 0,
  seriesData: []
});

// trainingForm表单校验规则
let trainingFormRules: any = {
  trainingCode: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    }
  ],

  trainingName: [
    {
      required: true,
      message: '请输入培训主题',
      trigger: 'blur'
    }
  ],

};
let searchForm = reactive({
  searchValue: '',
  year: null
});
const typeOptions = reactive([
  {
    name: '线下培训',
    value: 0
  },
  {
    name: '线上培训',
    value: 1
  }
]);
const userOptions = reactive([]);
const knowledgeTreeOptions = reactive([]);
let saveLoading = ref(false); //保存
const defaultProps = {
  children: 'children',
  label: 'name'
};

// 方法定义区 =============================================================
onMounted(() => {
  getUserList();
  getTrainingList();
  getKnowledgeTreeList();
});

function initChart() {
  const myChart = echarts.init(document.getElementById('dbBarCharts') as HTMLElement);
  //双柱状图(危急值)
  myChart.setOption({
    title: {
      text: '签到统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: formatter
    },
    legend: {
      orient: 'vertical',
      left: 'right'
    },
    grid: {
      x: 30,
      y: 100,
      x2: 30,
      y2: 100
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: trainingForm.seriesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
  window.addEventListener('resize', function () {
    myChart.resize();
  });
}

// 获取人员列表
function getUserList() {
  userOptions.length = 0;
  const url = '/api/user/getUserInfoList';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        userOptions.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 获取知识树型数据
function getKnowledgeTreeList() {
  knowledgeTreeOptions.length = 0;
  const url = '/api/wk/wkKnowledge/getKnowledgeTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        knowledgeTreeOptions.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取列表信息
function getTrainingList() {
  trainingList.length = 0;
  const url = '/wk/training/plan/getTrainingPlanList';
  proxy.$http
    .get(url, { params: { keyWord: searchForm.searchValue } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        trainingList.push(...res.data);
        currentChangeEvent({ row: trainingList[0] });
        const $xTable = proxy.$refs.trainingTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(trainingList[0]);
        }
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 行点击事件
function currentChangeEvent(row: any) {
  trainingForm.seriesData.length = 0;
  Object.assign(trainingForm, row.row);
  trainingForm.seriesData.push(...[trainingForm.signNo > 0 ? { value: trainingForm.signNo, name: '已签到' } : null, trainingForm.notSignNo > 0 ? { value: trainingForm.notSignNo, name: '未签到' } : null, trainingForm.refuseSignNo > 0 ? { value: trainingForm.refuseSignNo, name: '已拒绝' } : null]);
  initChart();
}

// 添加
function add() {
  Object.keys(trainingForm).forEach((key) => {
    switch (typeof trainingForm[key]) {
      case 'string':
        trainingForm[key] = '';
        break;
      case 'number':
        trainingForm[key] = 0;
        break;
    }
    if (key === 'seq') {
      trainingForm[key] = trainingList.length + 1;
    }
    if (Array.isArray(trainingForm[key])) {
      trainingForm[key].length = 0;
    }
  });
}
// 保存
function save() {
  let url = '';
  if (trainingForm.id == '' || trainingForm.id == null || trainingForm.id == undefined) {
    url = '/wk/training/plan/addTrainingPlan';
  } else {
    url = '/wk/training/plan/updateTrainingPlan';
  }
  const el: any = proxy.$refs.trainingFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      //校验
      return false;
    }
    let chileList = findAllNodes(knowledgeTreeOptions);
    trainingForm.knowledgeList = chileList
      .map((item) => {
        if (trainingForm.knowledgeIds.includes(item.id)) {
          return { id: item.id, title: item.name };
        }
        return null;
      })
      .filter((item) => !isEmpty(item));
    proxy.$http
      .post(url, trainingForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        getTrainingList();
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  });
}

// 发布
function release() {
  trainingForm.status = 1;
  save();
}
// 删除
function handleDelete() {
  const $xTable = proxy.$refs.trainingTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/training/plan/deleteTrainingPlanByIds';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getTrainingList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

function formatterType({ cellValue }) {
  const item = typeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}

function formatterStatus(cellValue) {
  return cellValue === 1 ? '发布' : '暂存';
}

// 图标弹框显示
function formatter(params) {
  let str = '';
  let obj = { 0: '未签到', 1: '已签到', 2: '已拒绝' };
  if (trainingForm.sysUserList && trainingForm.sysUserList.length > 0) {
    trainingForm.sysUserList.filter((item) => obj[item.differ] === params.data.name).forEach((item) => (str += item.realname + '<br/>'));
  }
  return str;
}

function findAllNodes(array) {
  let resultArray = [];
  for (let index = 0; index < array.length; index++) {
    resultArray.push(...findLeafNodes(array[index]));
  }
  return resultArray;
}

function findLeafNodes(node) {
  if (node.children.length === 0) {
    return [node];
  }
  return node.children.reduce((leafNodes, child) => {
    return leafNodes.concat(findLeafNodes(child));
  }, []);
}
</script>

<style lang="scss" scoped>
#training {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .trainingBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 30px);
          .el-tab-pane {
            height: 100%;
          }
          #pane-0 {
            .el-form {
              position: relative;
              height: 100%;
            }
          }
          // echarts图大小(挪到el-form里不生效)
          .barChartss {
            width: 310px;
            height: 300px;
            position: absolute;
            top: 10px;
            right: 20px;
          }
        }
      }
    }
  }
}
</style>
